package com.heima.wemedia.listener;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ApCommentConstants;
import com.heima.common.constants.HotArticleConstants;
import com.heima.model.article.mess.ArticleVisitStreamMess;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsStatistics;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmNewsStatisticsService;
import com.heima.wemedia.service.WmStatisticsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

/**
 * @author: Zqr
 * 监听文章评论相关操作后发送的kafaka消息,更新wm_news_statistics表中的comment评论数量
 */
@Slf4j
@Component
public class WmNewsStatisticsListener {
    @Autowired
    private WmNewsStatisticsService wmNewsStatisticsService;
    @Autowired
    private WmNewsMapper wmNewsMapper;

    @KafkaListener(topics = ApCommentConstants.AP_COMMENT_STREAM_OUT_SYNC_ARTICLE)
    public void onMessage(String msg) {
        if (StringUtils.isNotBlank(msg)) { //{"articleId":123,"add":"1"}
            log.info("WmNewsStatisticsListener-监听到kafka消息,开始更新wm_news_statistics表评论数量...");
            Map map = JSON.parseObject(msg, Map.class);
            //TODO
            long articleId = Long.valueOf(map.get("articleId").toString());
            int commentCount = Integer.parseInt(map.get("add").toString());
            //作者
            WmNews wmNews = wmNewsMapper.selectOne(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getArticleId, articleId)
                    .select(WmNews::getUserId));
            Integer authorId = wmNews.getUserId();//文章作者id,authorId

            //wm_news_statistic表插入数据
            WmNewsStatistics dbwmNewsStatistics = isExist(articleId);
            if (dbwmNewsStatistics == null) {
                //db中不存在该条记录,做新增操作 ,comment字段
                dbwmNewsStatistics.setUserId(authorId);
                dbwmNewsStatistics.setArticle(articleId);
                dbwmNewsStatistics.setReadCount(0);
                dbwmNewsStatistics.setComment(commentCount);
                dbwmNewsStatistics.setFollow(0);
                dbwmNewsStatistics.setCollection(0);
                dbwmNewsStatistics.setForward(0);
                dbwmNewsStatistics.setLikes(0);
                dbwmNewsStatistics.setUnlikes(0);
                dbwmNewsStatistics.setUnfollow(0);
                dbwmNewsStatistics.setBurst("");
                dbwmNewsStatistics.setCreatedTime(new Date());

                //保存
                wmNewsStatisticsService.save(dbwmNewsStatistics);

            } else {
                //db中存在该条文章的记录,做更新comment字段操作
                dbwmNewsStatistics.setComment((dbwmNewsStatistics.getComment() + commentCount) < 0 ? 0 : dbwmNewsStatistics.getComment() + commentCount);

                //更新
                wmNewsStatisticsService.updateById(dbwmNewsStatistics);
            }


        }
    }

    //监听热点文章流式计算的数据,更新wm_news_statistics文章的 COLLECTION:0,COMMENT:0,LIKES:0,VIEWS:0 数据
    @KafkaListener(topics = HotArticleConstants.HOT_ARTICLE_INCR_HANDLE_TOPIC)
    public void onMessage2(String msg) {
        if (StringUtils.isNotBlank(msg)) {
            //判断db中是否存在数据当前article的相关数据
            ArticleVisitStreamMess mess = JSON.parseObject(msg, ArticleVisitStreamMess.class);
            Long articleId = mess.getArticleId();
            int view = mess.getView();
            int collect = mess.getCollect();
            int comment = mess.getComment();
            int like = mess.getLike();

            WmNews wmNews = wmNewsMapper.selectOne(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getArticleId, articleId)
                    .select(WmNews::getUserId));
            Integer authorId = wmNews.getUserId();//文章作者id,authorId

            WmNewsStatistics dbwmNewsStatistics = isExist(articleId);
            if (dbwmNewsStatistics == null) {
                //db中不存在该条记录,做新增操作   COLLECTION:0,COMMENT:0,LIKES:0,VIEWS:0 数据
                dbwmNewsStatistics.setUserId(authorId);
                dbwmNewsStatistics.setArticle(articleId);//文章id
                dbwmNewsStatistics.setReadCount(view); //阅读量
                dbwmNewsStatistics.setComment(comment); //评论量
                dbwmNewsStatistics.setFollow(0);//关注量
                dbwmNewsStatistics.setCollection(collect); //收藏量
                dbwmNewsStatistics.setForward(0); //转发量
                dbwmNewsStatistics.setLikes(like); // 点赞量
                dbwmNewsStatistics.setUnlikes(0); //不喜欢
                dbwmNewsStatistics.setUnfollow(0); //取消关注量
                dbwmNewsStatistics.setBurst("");
                dbwmNewsStatistics.setCreatedTime(new Date());
                wmNewsStatisticsService.save(dbwmNewsStatistics);

            } else {
                //db中存在该条文章的记录,做更新  COLLECTION:0,COMMENT:0,LIKES:0,VIEWS:0 数据

                dbwmNewsStatistics.setReadCount((dbwmNewsStatistics.getReadCount() + view) < 0 ? 0 : dbwmNewsStatistics.getReadCount() + view);
                dbwmNewsStatistics.setCollection((dbwmNewsStatistics.getCollection() + collect) < 0 ? 0 : dbwmNewsStatistics.getCollection() + collect);
                dbwmNewsStatistics.setComment((dbwmNewsStatistics.getComment() + comment) < 0 ? 0 : dbwmNewsStatistics.getComment() + comment);
                dbwmNewsStatistics.setLikes((dbwmNewsStatistics.getLikes() + like) < 0 ? 0 : dbwmNewsStatistics.getLikes() + like);
                //更新
                wmNewsStatisticsService.updateById(dbwmNewsStatistics);
            }
        }
    }

    /**
     * 根据文章id判断数据库中是否存在当前记录,如果存在就返回当前查询记录;
     * 如果不存在就返回null
     *
     * @param articleId
     * @return
     */
    private WmNewsStatistics isExist(Long articleId) {

        WmNewsStatistics wmNewsStatistics = wmNewsStatisticsService.getOne(Wrappers.<WmNewsStatistics>lambdaQuery()
                .eq(WmNewsStatistics::getArticle, articleId));
        if (wmNewsStatistics != null) {
            return wmNewsStatistics;
        }
        return null;
    }
}
